<?php

namespace Home\Service;

use Home\DAO\WeixinDAO;

/**
 * 微信接口 Service
 *
 * @author 李静波
 */
class WeixinAPIService extends PSIBaseService {

	private function httpsRequest($url, $data = null) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (! empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}

	public function getWeixinConfig() {
		$wd = new WeixinDAO();
		$config = $wd->getWeixinConfig();
		
		return $config;
	}

	/**
	 * 获得当前用户的OpenId
	 */
	public function getOpenId($code) {
		$config = $this->getWeixinConfig();
		
		$appId = $config["appId"];
		$appSecret = $config["appSecret"];
		
		$isReleased = $config["isReleased"];
		if ($isReleased == 1) {
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
			$result = $this->httpsRequest($url);
			$jsoninfo = json_decode($result, true);
			$openId = $jsoninfo["openid"];
			
			return $openId;
		} else {
			// 本地开发环境
			return $this->genLocalMockOpenId();
		}
	}

	/**
	 * 本地开发环境中，模拟生成一个微信OpenId
	 */
	public function genLocalMockOpenId() {
		return "psi_test_open_id";
	}

	/**
	 * 把微信OpenId保存在Session中
	 *
	 * @param string $openId        	
	 */
	public function setOpenIdIntoSession($openId) {
		session("psi_weixin_open_id", $openId);
	}

	/**
	 * 从Seesion中获得微信OpenId
	 */
	public function getOpenIdFromSession() {
		return session("psi_weixin_open_id");
	}
}